<?php

/**
 * Base actions for the jfJQMAmobeeAdsPlugin jfPortableDevice module.
 * 
 * @package     jfJQMAmobeeAdsPlugin
 * @subpackage  actions
 * @author      Jonas Fischer <info@jonasfischer.net>
 * @version     SVN: $Id: BaseActions.class.php 12534 2008-11-01 13:38:27Z Kris.Wallsmith $
 */
abstract class BasejfJQMAmobeeAdsActions extends sfActions
{

  public function executeProxy() {
    $this->getResponse()->setContentType('application/javascript');
    
    $proxy = new jfJQMAmobeeAdsProxy();
    try {
    	return $this->renderText($proxy->execute());
    }
    catch (jfJQMAmobeeAdsException $e) {
    	$this->getResponse()->setStatusCode($e->getCode());
    	return $this->renderText($e->getMessage());
    }
  }
  
  public function executeJsProxy(sfWebRequest $request) {
  	$url = $request->getParameter('url');
  
  	$this->validateUrl($url);
  
  	$ch = curl_init();
  	curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml; charset=utf-8"));
  	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  
  	if ($request->isMethod('post')) {
  		curl_setopt($ch, CURLOPT_POST, 1);
  		curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getParameter('postData'));
  	}
  
  	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
  	curl_setopt($ch, CURLOPT_TIMEOUT, 40);
  	curl_setopt($ch, CURLOPT_URL, $url);
  
  	$content = curl_exec($ch);
  
  	$response = $this->getResponse();
  	$expireTime = 1800;
  	$response->addHttpMeta('Cache-Control', 'max-age='.$expireTime.', public, stale-while-revalidate=180, stale-if-error='.$expireTime*3);
  	$response->setStatusCode(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  	$response->setContentType(curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
  
  	return $this->renderText($content);
  }
  
  private function validateUrl($url) {
  	$whitelist = jfJQMAmobeeAds::getConfig('jsProxyUrlWhiteListPatterns', array());

  	foreach ($whitelist as $pattern) {
  		if (preg_match($pattern, $url)) {
  			return true;
  		}
  	}

  	throw new jfJQMAmobeeAdsException('Url not whitelisted: '.htmlspecialchars($url));
  }

}
